package com.starxg.m3u8.parser;

import java.io.File;
import java.math.BigDecimal;
import java.net.URL;
import java.util.Objects;

import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleObjectProperty;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;

/**
 * M3U8Item
 *
 * @author huangxingguang@lvmama.com
 * @date 2020-08-19 16:26
 */
@Getter
@Setter
@AllArgsConstructor
public class M3U8Item {
    static final String PREFIX = "#EXTINF";

    /**
     * key
     */
    private M3U8Key key;

    /**
     * 分片名称
     */
    private String name;

    /**
     * 分片地址
     */
    private URL url;

    /**
     * 分片时长
     */
    private BigDecimal time;

    /**
     * 文件保存的位置
     */
    private File savePath;

    /**
     * 下载失败的原因
     */
    private Throwable error;

    /**
     * 读取的长度，用于断点传序
     */
    private volatile int read;

    /**
     * 分片文件字节长度
     */
    private volatile long total;

    /**
     * 进度
     */
    private volatile SimpleDoubleProperty progress = new SimpleDoubleProperty(0.0D);

    /**
     * 当前状态
     */
    private volatile SimpleObjectProperty<M3U8ItemStatus> status = new SimpleObjectProperty<>();

    protected M3U8Item() {
    }

    public M3U8ItemStatus getStatus() {
        return status.get();
    }

    public SimpleObjectProperty<M3U8ItemStatus> statusProperty() {
        return status;
    }

    public void setStatus(M3U8ItemStatus status) {
        this.status.set(status);
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (!(o instanceof M3U8Item)) {
            return false;
        }
        M3U8Item m3U8Item = (M3U8Item) o;
        return Objects.equals(url, m3U8Item.url);
    }

    @Override
    public int hashCode() {
        return Objects.hash(url);
    }

    public double getProgress() {
        return progress.get();
    }

    public void setProgress(double progress) {
        this.progress.set(progress);
    }

    public SimpleDoubleProperty progressProperty() {
        return progress;
    }

    public boolean canDownload() {
        return !(getStatus() == M3U8ItemStatus.PAUSED || getStatus() == M3U8ItemStatus.SUCCEEDED);
    }

}